package com.alex.formates.qd;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

import android.util.Log;

import com.alex.books.BaseBook;
import com.alex.books.Chapter;
import com.alex.formates.ReaderPlugin;

/**
 * 
 * 解析txt文件
 * 
 * @author Alex.Lu
 * 
 */
public class QDPlugin3 extends ReaderPlugin {

	private int mBufBegin;
	private int mBufEnd;
	private byte[] bytes;
	private long mMbBufLen = 3000;
	private Vector<String> mContent = new Vector<String>();
	private int LEN = 1024*10;
	private int allLength;
	Vector<String> strings = new Vector<String>();

	
	@Override
	public Object decode(BaseBook book, File file) {
		// TODO Auto-generated method stub
		mFile = file;
		allLength = (int) book.mLength;
		mBufBegin = mBufEnd = (int) book.mReaderingInfo.mMarkPos;
		readContent0(file, mBufBegin);
		return null;
	}

	public void setBookReposition(BaseBook book, File file) {

	}

	@Override
	public boolean isFirstChapter() {
		// TODO Auto-generated method stub
		if (mBaseBook.mReaderingInfo.mIndex <= 0) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isLastChapter() {
		// TODO Auto-generated method stub
		if (mBaseBook.mReaderingInfo.mIndex >= mBaseBook.mChapters.size() - 1) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isFirstPage() {
		// TODO Auto-generated method stub
		if (mBaseBook.mReaderingInfo.mIndex <= 0
				&& mBufBegin <= mBaseBook.mChapters.get(0).mPosBegin) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isLastPage() {
		// TODO Auto-generated method stub
		if (mBaseBook.mReaderingInfo.mIndex >= mBaseBook.mChapters.size() - 1
				&& mBufEnd >= mBaseBook.mReaderingInfo.mCurChapter.mPosEnd) {
			return true;
		}
		return false;
	}

	@Override
	public String nextChapter() {
		// TODO Auto-generated method stub
		if (mBaseBook.mReaderingInfo.mIndex + 1 < mBaseBook.mChapters.size()) {
			mBaseBook.mReaderingInfo.mIndex++;
			mBaseBook.mReaderingInfo.mCurChapter = mBaseBook.mChapters
					.get(mBaseBook.mReaderingInfo.mIndex);
			mBaseBook.mReaderingInfo.mMarkPos = mBaseBook.mReaderingInfo.mCurChapter.mPosBegin;
		}
		mBufEnd = (int) mBaseBook.mReaderingInfo.mMarkPos;
		StringBuffer text = new StringBuffer();
		mLines.clear();
		mLines = getPageNextText(mBaseBook.mReaderingInfo.mCurChapter.mPosEnd);
		for (int i = 0; i < mLines.size(); i++) {
			text.append(mLines.get(i) + "\n");
		}
		mBaseBook.mReaderingInfo.mCurText = text.toString();
		return text.toString();
	}

	@Override
	public String nextPage() {
		// TODO Auto-generated method stub
		if (mBufEnd >= mBaseBook.mReaderingInfo.mCurChapter.mPosEnd
				&& mBaseBook.mReaderingInfo.mIndex + 1 < mBaseBook.mChapters
						.size()) {
			mBaseBook.mReaderingInfo.mIndex++;
			mBaseBook.mReaderingInfo.mCurChapter = mBaseBook.mChapters
					.get(mBaseBook.mReaderingInfo.mIndex);
			mBaseBook.mReaderingInfo.mMarkPos = mBaseBook.mReaderingInfo.mCurChapter.mPosBegin;
			mBufEnd = (int) mBaseBook.mReaderingInfo.mCurChapter.mPosBegin;
			Log.e("nextPage", "mBaseBook.mReaderingInfo:"
					+ mBaseBook.mReaderingInfo.mCurChapter.mChapterName);
		}

		StringBuffer text = new StringBuffer();
		mLines.clear();
		mLines = getPageNextText(mBaseBook.mReaderingInfo.mCurChapter.mPosEnd);
		for (int i = 0; i < mLines.size(); i++) {
			text.append(mLines.get(i) + "\n");
		}
		mBaseBook.mReaderingInfo.mCurText = text.toString();
		return text.toString();
	}

	@Override
	public String previousChapter() {
		// TODO Auto-generated method stub
		if (mBaseBook.mReaderingInfo.mIndex - 1 >= 0) {
			mBaseBook.mReaderingInfo.mIndex--;
			mBaseBook.mReaderingInfo.mCurChapter = mBaseBook.mChapters
					.get(mBaseBook.mReaderingInfo.mIndex);
			mBaseBook.mReaderingInfo.mMarkPos = mBaseBook.mReaderingInfo.mCurChapter.mPosBegin;
		}
		mBufEnd = (int) mBaseBook.mReaderingInfo.mMarkPos;
		StringBuffer text = new StringBuffer();
		mLines.clear();
		mLines = getPageNextText(mBaseBook.mReaderingInfo.mCurChapter.mPosEnd);
		for (int i = 0; i < mLines.size(); i++) {
			text.append(mLines.get(i) + "\n");
		}
		mBaseBook.mReaderingInfo.mCurText = text.toString();
		return text.toString();
	}

	@Override
	public String previousPage() {
		// TODO Auto-generated method stub
		if (mBufBegin <= mBaseBook.mReaderingInfo.mCurChapter.mPosBegin
				&& mBaseBook.mReaderingInfo.mIndex - 1 >= 0) {
			mBaseBook.mReaderingInfo.mIndex--;
			mBaseBook.mReaderingInfo.mCurChapter = mBaseBook.mChapters
					.get(mBaseBook.mReaderingInfo.mIndex);
			mBaseBook.mReaderingInfo.mMarkPos = mBaseBook.mReaderingInfo.mCurChapter.mPosEnd;
			mBufBegin = (int) mBaseBook.mReaderingInfo.mMarkPos;
		}

		StringBuffer text = new StringBuffer();
		mLines.clear();
		mLines = getPagePrevious();

		for (int i = 0; i < mLines.size(); i++) {
			text.append(mLines.get(i) + "\n");
			Log.d("previousPage " + i, mLines.get(i));
		}
		mBaseBook.mReaderingInfo.mCurText = text.toString();
		return text.toString();
	}

	@Override
	public String refreshPage() {
		// TODO Auto-generated method stub
		mBufEnd = (int) mBaseBook.mReaderingInfo.mMarkPos;
		StringBuffer text = new StringBuffer();
		mLines.clear();
		mLines = getPageNextText(Integer.valueOf(mBaseBook.mWordNumber));
		for (int i = 0; i < mLines.size(); i++) {
			text.append(mLines.get(i) + "\n");
		}
		mBaseBook.mReaderingInfo.mCurText = text.toString();
		return text.toString();
	}

	public Object generatedCatalog2(BaseBook book, File file, String keywords) {
		// TODO Auto-generated method stub
		mFile = file;
		Vector<Chapter> vec = new Vector<Chapter>();
		BufferedInputStream fis;

		try {
			fis = new BufferedInputStream(new FileInputStream(file));
			InputStreamReader reader = new InputStreamReader(fis, "gb2312");// 用5M的缓冲读取文本文件
			StringBuffer sbuf = new StringBuffer();
			allLength = 0;
			int postion = 0;
			int outpostsion = 0;
			String strParagraph = null;
			String chapterName = "";
			int in = 0;
			int ch = -1;
			char[] chars = new char[10 * 1024];
			while ((ch = reader.read(chars)) != -1) {
				// TODO: write your business

				outpostsion = allLength;
				allLength += ch;
				sbuf.append(chars);
				int inpostion = 0;
				while (inpostion < ch) {
					strParagraph = readParagraphNext0(sbuf.toString(),
							inpostion);
					int endPos = sbuf.length();
					if (strParagraph.length() < 40
							&& strParagraph.contains(keywords) && strParagraph.contains("第")) {
						if (vec.size() == 0) {
							endPos = inpostion;
							Chapter chapter = new Chapter();
							chapter.mBookId = book.mBookId;
							chapter.mChapterName = chapterName;
							chapter.mPosBegin = 0;
							chapter.mPosEnd = (int) endPos;
							chapter.mLength = chapter.mPosEnd
									- chapter.mPosBegin;
							System.err.println(chapter.mChapterName
									+ "  beginPos:" + chapter.mPosBegin
									+ "  endPos:" + chapter.mPosEnd
									+ "   chapter.mLength:" + chapter.mLength);
							if(chapter.mLength!=0){
								vec.add(chapter);
							}
							
						} else {
							endPos = outpostsion + inpostion;
							Chapter chapter = new Chapter();
							chapter.mBookId = book.mBookId;
							chapter.mChapterName = chapterName;
							chapter.mPosBegin = postion + chapterName.length();
							chapter.mPosEnd = (int) endPos;
							chapter.mLength = chapter.mPosEnd
									- chapter.mPosBegin;
							System.err.println(chapter.mChapterName
									+ "  beginPos:" + chapter.mPosBegin
									+ "  endPos:" + chapter.mPosEnd
									+ "   chapter.mLength:" + chapter.mLength);
							vec.add(chapter);
						}
						postion = outpostsion + inpostion;
						chapterName = strParagraph;
					}
					inpostion += strParagraph.length();
				}
				sbuf.setLength(0);
			}
			Log.e("", "in:" + allLength);
			reader.close();
			fis.close();

			Chapter chapter = new Chapter();
			chapter.mBookId = book.mBookId;
			chapter.mChapterName = chapterName;
			chapter.mPosBegin = postion + chapterName.length();
			chapter.mPosEnd = allLength;
			chapter.mLength = chapter.mPosEnd - chapter.mPosBegin;
			vec.add(chapter);
			System.err.println(chapter.mChapterName
					+ "  beginPos:" + chapter.mPosBegin
					+ "  endPos:" + chapter.mPosEnd
					+ "   chapter.mLength:" + chapter.mLength);
			book.mChapters = vec;
			book.mChapterNumber = "" + book.mChapters.size();
			book.mWordNumber = String.valueOf(allLength);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return vec;
	}

	@Override
	public Object generatedCatalog(BaseBook book, File file, int mode) {
		// TODO Auto-generated method stub
		mFile = file;
		Vector<Chapter> vec = new Vector<Chapter>();
		BufferedInputStream fis;

		try {
			fis = new BufferedInputStream(new FileInputStream(file));
			InputStreamReader reader = new InputStreamReader(fis, "gb2312");// 用5M的缓冲读取文本文件
			StringBuffer sbuf = new StringBuffer();
			allLength = 0;
			int postion = 0;
			int outpostsion = 0;
			String strParagraph = null;
			String chapterName = "";
			int in = 0;
			int ch = -1;
			char[] chars = new char[10 * 1024];
			while ((ch = reader.read(chars)) != -1) {
				// TODO: write your business

				outpostsion = allLength;
				allLength += ch;
				sbuf.append(chars);
				int inpostion = 0;
				while (inpostion < ch) {
					strParagraph = readParagraphNext0(sbuf.toString(),
							inpostion);
					int endPos = sbuf.length();
					if (strParagraph.length() < 40
							&&strParagraph.contains("###")) {
						if (vec.size() == 0) {
							endPos = inpostion;
							Chapter chapter = new Chapter();
							chapter.mBookId = book.mBookId;
							chapter.mChapterName = chapterName;
							chapter.mPosBegin = 0;
							chapter.mPosEnd = (int) endPos;
							chapter.mLength = chapter.mPosEnd
									- chapter.mPosBegin;
							System.err.println(chapter.mChapterName
									+ "  beginPos:" + chapter.mPosBegin
									+ "  endPos:" + chapter.mPosEnd
									+ "   chapter.mLength:" + chapter.mLength);
							if(chapter.mLength!=0){
								vec.add(chapter);
							}
							
						} else {
							endPos = outpostsion + inpostion;
							Chapter chapter = new Chapter();
							chapter.mBookId = book.mBookId;
							chapter.mChapterName = chapterName;
							chapter.mPosBegin = postion + chapterName.length();
							chapter.mPosEnd = (int) endPos;
							chapter.mLength = chapter.mPosEnd
									- chapter.mPosBegin;
							System.err.println(chapter.mChapterName
									+ "  beginPos:" + chapter.mPosBegin
									+ "  endPos:" + chapter.mPosEnd
									+ "   chapter.mLength:" + chapter.mLength);
							vec.add(chapter);
						}
						postion = outpostsion + inpostion;
						chapterName = strParagraph;
					}
					inpostion += strParagraph.length();
				}
				sbuf.setLength(0);
			}
			Log.e("", "in:" + allLength);
			reader.close();
			fis.close();

			Chapter chapter = new Chapter();
			chapter.mBookId = book.mBookId;
			chapter.mChapterName = chapterName;
			chapter.mPosBegin = postion + chapterName.length();
			chapter.mPosEnd = allLength;
			chapter.mLength = chapter.mPosEnd - chapter.mPosBegin;
			vec.add(chapter);
			System.err.println(chapter.mChapterName
					+ "  beginPos:" + chapter.mPosBegin
					+ "  endPos:" + chapter.mPosEnd
					+ "   chapter.mLength:" + chapter.mLength);
			book.mChapters = vec;
			book.mChapterNumber = "" + book.mChapters.size();
			book.mWordNumber = String.valueOf(allLength);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		int end = (int) mMbBufLen;
		if (end > 200) {
			end = 200;
		}
		readContent0(file, 0);
		
		if(book.mAttach1 != null){
			if(!book.mAttach1.equals("1")){
				book.mAboutBook = tx.substring(0, end);
			}
		}else{
			book.mAboutBook = tx.substring(0, end);
		}
		
		return vec;
	}

	/**
	 * 获取下一页数据
	 * 
	 * @param endPos
	 * @return
	 */
	private Vector<String> getPageNextText(long endPos) {
		mBaseBook.mReaderingInfo.mMarkPos = mBufEnd;
		mBufBegin = mBufEnd;
		String strParagraph = "";
		Vector<String> lines = new Vector<String>();
		while (lines.size() <= 0) {
			while (lines.size() < mReaderFormate.mLineCount && mBufEnd < endPos) {
				strParagraph = readParagraphNext(mBufEnd);
				mBufEnd += strParagraph.length();
				String strReturn = "";
				if (strParagraph.indexOf("\n") != -1) {
					strReturn = "\n";
					strParagraph = strParagraph.replaceAll("\n", "");
				}

				if (strParagraph.length() == 0) {
					lines.add(strParagraph);
				}
				while (strParagraph.length() > 0) {
					int nSize = mReaderFormate.mPaint.breakText(strParagraph,
							true, mReaderFormate.mPageW, null);

					lines.add(strParagraph.substring(0, nSize));
					strParagraph = strParagraph.substring(nSize);
					if (lines.size() >= mReaderFormate.mLineCount) {
						break;
					}
				}
				if (strParagraph.length() != 0) {
					mBufEnd -= (strParagraph + strReturn).length();
				}
			}
		}
		return lines;
	}

	private Vector<String> getPagePrevious() {
		if (mBufBegin <= mBaseBook.mChapters.get(0).mPosBegin)
			mBufBegin = (int) mBaseBook.mChapters.get(0).mPosBegin;
		mBufEnd = mBufBegin;
		Vector<String> lines = new Vector<String>();
		String strParagraph = "";
		while (lines.size() <= 0) {
			while (lines.size() < mReaderFormate.mLineCount && mBufBegin >= 0) {
				Vector<String> paraLines = new Vector<String>();
				strParagraph = readParagraphPrevious(mBufBegin);
				mBufBegin -= strParagraph.length();

				strParagraph = strParagraph.replaceAll("\r\n", "");
				strParagraph = strParagraph.replaceAll("\n", "");
				if (strParagraph.length() == 0) {
					paraLines.add(strParagraph);
				}
				while (strParagraph.length() > 0) {
					int nSize = mReaderFormate.mPaint.breakText(strParagraph,
							true, mReaderFormate.mPageW, null);
					paraLines.add(strParagraph.substring(0, nSize));
					strParagraph = strParagraph.substring(nSize);
				}
				lines.addAll(0, paraLines);
			}
			while (lines.size() > mReaderFormate.mLineCount) {
				mBufBegin += lines.get(0).length();
				lines.remove(0);
			}
		}
		mBaseBook.mReaderingInfo.mMarkPos = mBufBegin;
		return lines;
	}

	/**
	 * 读取上一段落
	 * 
	 * @param nFromPos
	 * @return
	 */
	private String readParagraphPrevious(int nFromPos) {
		if (mAmnout >= LEN && nFromPos <= mAmnout) {
			readContent0(mFile, mAmnout - LEN);
		}
		int pos = (nFromPos - 1) / LEN;
		int off = nFromPos % LEN;
		String text = tx.substring(0, nFromPos - pos * LEN);
		int end = 0;
		if ((end = text.lastIndexOf("\n")) != -1) {
		}
		if (end < 0) {
			end = 0;
		}
		return text.substring(end, nFromPos - pos * LEN);
	}

	private String readParagraphNext(int nFromPos) {
		if (nFromPos >= mAmnout + LEN) {
			readContent0(mFile, mAmnout + LEN);
		}
		int pos = nFromPos / LEN;
		int off = nFromPos % LEN;
		String text = tx;
		int end = 0;
		if ((end = text.indexOf("\n", nFromPos - pos * LEN)) != -1) {
			end += 1;
		}

		// Log.e("", "nFromPos:"+nFromPos + "   end:"+end);
		if (end == -1 || end >= mMbBufLen) {
			end = (int) mMbBufLen;
		}
		return text.substring(nFromPos - pos * LEN, end);
	}

	private String readParagraphNext0(String text, int nFromPos) {
		int end = 0;
		if ((end = text.indexOf("\n", nFromPos)) != -1) {
			end += 1;
		}

		// Log.e("", "nFromPos:"+nFromPos + "   end:"+end);
		if (end == -1 || end >= text.length()) {
			end = (int) text.length();
		}
		return text.substring(nFromPos, end);
	}

	private String tx = "";
	private long mAmnout;
	private File mFile;

	private void readContent0(File file, long amnout) {
		mAmnout = (amnout / LEN) * LEN;
		Log.e("", "mAmnout" + mAmnout);
		BufferedInputStream fis;
		try {
			fis = new BufferedInputStream(new FileInputStream(file));
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					fis, "gb2312"), 1024 * 1024);// 用5M的缓冲读取文本文件
			reader.skip(mAmnout);
			StringBuffer sbuf = new StringBuffer();
			char[] chars = new char[1024];
			int n = 0;
			while ((n = reader.read(chars)) != -1) {
				// TODO: write your business
				sbuf.append(chars);
				if (sbuf.length() > LEN) {
					tx = sbuf.toString();
					sbuf.setLength(0);
					break;
				}
			}

			if (sbuf.length() > 0 && sbuf.length() <= LEN) {
				tx = sbuf.toString();
			} else {
				tx = tx.substring(0, LEN);
			}
			reader.close();
			fis.close();

			mMbBufLen = tx.length();

			Log.e("", "mMbBufLen:" + mMbBufLen);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
